﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace HosPlat.API
{
    public class SocketUtil
    {
        public static string Send(string ip, int port, string seddmsg)
        {
            string returnData = "";
            // This constructor arbitrarily assigns the local port number.
            UdpClient udpClient = new UdpClient();
            try
            {
                IPAddress ipAddr = IPAddress.Parse(ip);
                udpClient.Connect(ipAddr, port);

                // Sends a message to the host to which you have connected.

                var sendBytes = CRC.StringToHexByte(seddmsg);

                int i = udpClient.Send(sendBytes, sendBytes.Length);

                //IPEndPoint object will allow us to read datagrams sent from any source.
                IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
                bool isReturn = false;
                int findCount = 0;
                while (!isReturn)
                {
                    if (udpClient.Client.Available > 0)
                    {
                        // Blocks until a message returns on this socket from a remote host.
                        byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
                        returnData = CRC.ByteArrayToHexString(receiveBytes);
                        int rlength = Int32.Parse(receiveBytes[2].ToString()) + 5;
                        int recNum = 0;
                        while (returnData.Length < rlength * 2 && recNum <100)
                        {
                            if (udpClient.Client.Available > 0)
                            {
                                byte[] receiveBytes2 = udpClient.Receive(ref RemoteIpEndPoint);
                                string r2 = CRC.ByteArrayToHexString(receiveBytes2);
                                returnData += r2;

                            }

                            Thread.Sleep(100);
                            recNum++;

                        }

                        isReturn = true;
                    }
                    Thread.Sleep(200);
                    if (findCount > 2)
                    {
                        break;
                    }
                    findCount++;
                }
                udpClient.Close();

               
            }
            catch (Exception e)
            {
                
            }

            return returnData;
        }

        

    }
}